package com.zhong.demo.viewpager2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import static androidx.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    private ViewPager2 viewPager2;
    private List<String>  dataList;
    private MainAdapter adapter;

    private TestLifeCycleView testLifeCycleView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager2 = findViewById(R.id.main_vp);

        testLifeCycleView = findViewById(R.id.test_lifecycle_view);
        getLifecycle().addObserver(testLifeCycleView.getLifeCycleObserver());

        dataList = new ArrayList<>();
        for(int i = 0; i < 5; i++){
            dataList.add("Item " + (i + 1));
        }

        initViewPager2();
    }

    /**
     * init viewpager2
     */
    private void initViewPager2(){
        //设置方向
        viewPager2.setOrientation(ORIENTATION_HORIZONTAL);

        adapter = new MainAdapter(MainActivity.this);
        viewPager2.setAdapter(adapter);

        getLifecycle().addObserver(testLifeCycleView.getLifeCycleObserver());
    }

    public class MainAdapter extends FragmentStateAdapter {

        public MainAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return new AFragment(dataList.get(position));
        }


        @Override
        public int getItemCount() {
            return dataList.size();
        }
    }
}
